// 引入Webpack的插件基类

class BannerWebpackPlugin {
  // 构造函数接收用户在webpack配置文件中传递的options
  constructor(options) {
    this.options = options;
  }

  // 实现apply方法，编写自定义逻辑
  apply(compiler) {
    // 钩入Webpack的编译生命周期
    compiler.hooks.emit.tap("MyWebpackPlugin", (compilation) => {
      // 在此执行你的逻辑
      console.log("Webpack compilation is happening...");
      const extensions = ["css", "js"];
      const assetFilter = Object.keys(compilation.assets).filter(
        (assetPath) => {
          const splitArr = assetPath.split(".");
          const ext = splitArr[splitArr.length - 1];
          return extensions.includes(ext);
        }
      );
      const { author } = this.options;
      const prefix = `/*author: ${author}*/`;
      assetFilter.forEach((item) => {
        const source = compilation.assets[item].source();
        compilation.assets[item] = {
          source() {
            return prefix + source;
          },
        };
        // item._source = prefix + item._source
      });
      // 必须调用回调函数，以避免Webpack编译流程出错
      // callback();
    });
  }
}

module.exports = BannerWebpackPlugin;
